package cn.aiyuan.controller;

import cn.aiyuan.properties.OssConfigurationProperties;
import cn.aiyuan.utils.FileUtil;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wy
 * @since  2020/9/22
 */
@RestController
@RequestMapping("/file")
public class UploadController {

    @Resource
    private OssConfigurationProperties configurationProperties;

    /**
     *上传文件
     * @param file 文件
     * @param dir 文件夹
     * @return 返回阿里访问全地址
     */
    @PostMapping("/upload")
    @SneakyThrows
    public List<String> uploadFiles(MultipartFile[] file, String dir) {
        List<String> ossUrls = new ArrayList<>();
        for (MultipartFile f : file) {
            String url = FileUtil.concatAllPath(dir, FileUtil.createUuIdName(f));
            // 上传到oss服务器
            boolean upload = configurationProperties.upload(f.getInputStream(), url);
            if (upload) {// 上传oss服务器成功
                // 获取文件路径
                String ossURL = configurationProperties.getFileOSSUrl(url);
                ossUrls.add(ossURL);
            }
        }
        return ossUrls;
    }

    @DeleteMapping("/del")
    public Boolean uploadFiles(String path) {
        return configurationProperties.delFile(path);
    }


}
